package com.softdev.system.generator.service;


import com.alibaba.fastjson2.JSONArray;
import com.alibaba.fastjson2.JSONObject;

import com.softdev.system.generator.util.FreemarkerUtil;
import com.softdev.system.generator.util.MapUtil;

import java.io.BufferedReader;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * GeneratorService
 *
 * @author zhengkai.blog.csdn.net
 */
public class GeneratorServiceImpl implements GeneratorService {

    String templateCpnfig = null;

    /**
     * 从项目中的JSON文件读取String
     *
     * @author zhengkai.blog.csdn.net
     */
    @Override
    public String getTemplateConfig(String dbDir) {
        String pathToFile = dbDir + "/genCodeTemplate.json";
        try (InputStream inputStream = new FileInputStream(pathToFile)) {
            templateCpnfig = new BufferedReader(new InputStreamReader(inputStream))
                    .lines().collect(Collectors.joining(System.lineSeparator()));
        } catch (IOException e) {
            System.out.println(e.getMessage());
        }
        return templateCpnfig;
    }

    /**
     * 根据配置的Template模板进行遍历解析，得到生成好的String
     *
     * @author zhengkai.blog.csdn.net
     */
    @Override
    public Map<String, String> getResultByParams(String dbDir, String type, Map<String, Object> params) throws Exception {
        Map<String, String> result = new HashMap<>(32);
        result.put("tableName", MapUtil.getString(params, "tableName"));
        JSONArray parentTemplates = JSONArray.parseArray(getTemplateConfig(dbDir));
        FreemarkerUtil utl = new FreemarkerUtil();
        utl.init(dbDir);
        String[] stringArray = type.split(";");
        ArrayList<String> arrayList = new ArrayList<>(Arrays.asList(stringArray));
        for (int i = 0; i < parentTemplates.size(); i++) {
            JSONObject parentTemplateObj = parentTemplates.getJSONObject(i);
            int sz = parentTemplateObj.getJSONArray("templates").size();
            for (int x = 0; x < sz; x++) {
                JSONObject childTemplate = parentTemplateObj.getJSONArray("templates").getJSONObject(x);
                String name = childTemplate.getString("name");
                // 如果找到相同的类型 就转换
                // 如果类型是*,表示要转全部的类型,否则只是转一种类型
                if ("[*]".equals(type) || arrayList.contains(name)) {
                    result.put(name, utl.processString(parentTemplateObj.getString("group") + "/" + childTemplate.getString("name") + ".ftl", params));
                }
            }
        }
        return result;
    }

}
